package com.astroway.livetest;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.OrientationEventListener;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.astroway.livetest.adapter.FaceGVAdapter;
import com.astroway.livetest.adapter.FaceVPAdapter;
import com.astroway.livetest.adapter.MessageAdapter;
import com.astroway.livetest.model.ChatEntity;
import com.astroway.livetest.model.CurLiveInfo;
import com.astroway.livetest.model.LiveInfoJson;
import com.astroway.livetest.model.MemberID;
import com.astroway.livetest.model.MessageModel;
import com.astroway.livetest.model.MySelfInfo;
import com.astroway.livetest.model.RoomInfoJson;
import com.astroway.livetest.presenters.LiveHelper;
import com.astroway.livetest.presenters.UserServerHelper;
import com.astroway.livetest.presenters.viewinface.LiveListView;
import com.astroway.livetest.presenters.viewinface.LiveView;
import com.astroway.livetest.util.Constants;
import com.astroway.livetest.util.SxbLog;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import com.tencent.TIMElem;
import com.tencent.TIMMessage;
import com.tencent.TIMTextElem;
import com.tencent.TIMUserProfile;
import com.tencent.av.TIMAvManager;
import com.tencent.ilivesdk.ILiveCallBack;
import com.tencent.ilivesdk.ILiveConstants;
import com.tencent.ilivesdk.core.ILiveRoomManager;
import com.tencent.ilivesdk.data.ILivePushRes;
import com.tencent.ilivesdk.view.AVRootView;
import com.tencent.ilivesdk.view.AVVideoView;
import com.tencent.livesdk.ILVLiveManager;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 崔健伟
 * @version V1.0
 * @Title: LiveActivity.java
 * @Package com.astroway.livetest
 * @Description:
 * @date 2017/2/10 14:12
 */
public class LiveActivity extends BaseActivity implements LiveListView, LiveView, View.OnClickListener {
    private static final String TAG = "LiveActivity";

    //    private static String HOST_ID = "cuijianwei0915";
    private static String HOST_ID = "";
    //    private static final String HOST_ID = "duxiaofeng";
    private static int ROOM_NUM = 10337;
    private static String PHONE_NUM = "";
    //    private static final int ROOM_NUM = 10268;

    private AVRootView avRootView;
    private ListView listView;
    private EditText editText;
    private Button button;
    private LinearLayout linearLayout;
    private ViewPager viewPager;
    private LinearLayout mDotsLayout;
    private RelativeLayout relativeLayout;
    private RelativeLayout messageRl;
    private RelativeLayout avrootViewRl;
    private ImageView allImage;
    private LiveHelper mLiveHelper;
    private List<ChatEntity> messageList;
    private ArrayList<ChatEntity> mTmpChatList;//缓冲队列
    private MessageAdapter messageAdapter;
    private List<View> views = new ArrayList<View>();
    private List<String> staticFacesList;
    // 7列3行
    private int columns = 7;
    private int rows = 3;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;
    private WindowManager wm;
    private AVVideoView avVideoView;

    private boolean isFull = false;

    /**
     * @author: cuijianwei
     * @time: 2016/11/27 10:21
     * @desc: 控制全屏
     **/
    private void setFullClick() {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }

    /**
     * @author: cuijianwei
     * @time: 2016/11/27 10:21
     * @desc: 控制半屏
     **/
    private void setHalfClick() {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        Log.d(TAG, "onConfigurationChanged: " + newConfig.orientation);
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            setFull();
        }
        if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            setHalf();
        }
    }

    private void setFull() {
        isFull = true;
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);// 设置全屏
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        avrootViewRl.setLayoutParams(params);
        messageRl.setVisibility(View.GONE);
        if (avVideoView == null) {
            avVideoView = avRootView.getViewByIndex(0);
        }
        avVideoView.setPosWidth(getWidth());
        avVideoView.setPosHeight(getHeight());
        allImage.setImageResource(R.drawable.half_icon);
    }

    private void setHalf() {
        isFull = false;
        this.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        params.height = this.getResources().getDimensionPixelOffset(R.dimen.avrootview_height);
        avrootViewRl.setLayoutParams(params);
        messageRl.setVisibility(View.VISIBLE);
        if (avVideoView == null) {
            avVideoView = avRootView.getViewByIndex(0);
        }
        avVideoView.setPosWidth(getWidth());
        avVideoView.setPosHeight(this.getResources().getDimensionPixelOffset(R.dimen.avrootview_height));
        allImage.setImageResource(R.drawable.all_icon);
    }

    private int getWidth() {
        int width = wm.getDefaultDisplay().getWidth();
        return width;
    }

    private int getHeight() {
        int height = wm.getDefaultDisplay().getHeight();
        return height;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);   // 不锁屏
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//去掉信息栏
        wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        setContentView(R.layout.activity_live);
        checkPermission();
        mLiveHelper = new LiveHelper(this, this);
        initData();
        initStaticFaces();
        initView();
        InitViewPager();
        MySelfInfo.getInstance().setIdStatus(Constants.MEMBER);
        CurLiveInfo.setHostID(HOST_ID);
        CurLiveInfo.setRoomNum(ROOM_NUM);
        //进入房间流程
        mLiveHelper.startEnterRoom();
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
        setFullImageClick();
    }

    private void setFullImageClick() {
        allImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isFull) {
                    setHalfClick();
                } else {
                    setFullClick();
                }
            }
        });
    }

    private void initData() {
        Intent intent = getIntent();
        HOST_ID = intent.getStringExtra("HostId");
        ROOM_NUM = intent.getIntExtra("RoomNum", 10268);
        PHONE_NUM = intent.getStringExtra("Phone");
        messageList = new ArrayList<>();
        mTmpChatList = new ArrayList<>();
    }

    private void initView() {
        listView = (ListView) findViewById(R.id.activity_live_lv);
        initListView();
        editText = (EditText) findViewById(R.id.activity_live_content_et);
        button = (Button) findViewById(R.id.activity_live_send_btn);
        button.setOnClickListener(this);
        linearLayout = (LinearLayout) findViewById(R.id.activity_live_face_img);
        linearLayout.setOnClickListener(this);
        viewPager = (ViewPager) findViewById(R.id.activity_live_face_vp);
        FaceVPAdapter mVpAdapter = new FaceVPAdapter(views);
        viewPager.setAdapter(mVpAdapter);
        mDotsLayout = (LinearLayout) findViewById(R.id.activity_live_ll);
        relativeLayout = (RelativeLayout) findViewById(R.id.activity_live_face_rl);
        avRootView = (AVRootView) findViewById(R.id.activity_live_av_root_view);
        messageRl = (RelativeLayout) findViewById(R.id.activitry_live_message_rl);
        avrootViewRl = (RelativeLayout) findViewById(R.id.activity_live_avrootview_rl);
        allImage = (ImageView) findViewById(R.id.img_all);
        //TODO 设置渲染层
        ILVLiveManager.getInstance().setAvVideoView(avRootView);
        avRootView.setGravity(AVRootView.LAYOUT_GRAVITY_LEFT);
        avRootView.setSubMarginY(getResources().getDimensionPixelSize(R.dimen.small_area_margin_top));
        avRootView.setSubMarginX(getResources().getDimensionPixelSize(R.dimen.small_area_marginright));
        avRootView.setSubPadding(getResources().getDimensionPixelSize(R.dimen.small_area_marginbetween));
        avRootView.setSubWidth(getResources().getDimensionPixelSize(R.dimen.small_area_width));
        avRootView.setSubHeight(getResources().getDimensionPixelSize(R.dimen.small_area_height));
        avVideoView = avRootView.getViewByIndex(0);
        avRootView.setSubCreatedListener(new AVRootView.onSubViewCreatedListener() {
            @Override
            public void onSubViewCreated() {
                toChangeRootView();
            }
        });
    }

    private void toChangeRootView() {
        for (int i = 1; i < ILiveConstants.MAX_AV_VIDEO_NUM; i++) {
            final int index = i;
            AVVideoView avRootView1 = avRootView.getViewByIndex(index);
            avRootView1.setGestureListener(new GestureDetector.SimpleOnGestureListener() {
                @Override
                public boolean onSingleTapConfirmed(MotionEvent e) {
                    avRootView.swapVideoView(0, index);
                    avVideoView = avRootView.getViewByIndex(0);
                    return super.onSingleTapConfirmed(e);
                }
            });
        }
    }

    private void initListView() {
        messageAdapter = new MessageAdapter(this, messageList);
        listView.setAdapter(messageAdapter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        ILiveRoomManager.getInstance().onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        ILiveRoomManager.getInstance().onPause();
        mLiveHelper.startExitRoom();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CurLiveInfo.setMembers(0);
        CurLiveInfo.setAdmires(0);
        CurLiveInfo.setCurrentRequestCount(0);
        avRootView.clearUserView();
        mLiveHelper.onDestory();
    }


    @Override
    public void showRoomList(UserServerHelper.RequestBackInfo result, ArrayList<RoomInfoJson> roomlist) {

    }

    @Override
    public void enterRoomComplete(int id_status, boolean succ) {
        //必须得进入房间之后才能初始化UI
        avRootView.getViewByIndex(0).setRotate(true);
        if (succ) {
            if (id_status == Constants.HOST) {
            } else {
                //发消息通知上线
                mLiveHelper.sendGroupCmd(Constants.AVIMCMD_ENTERLIVE, "");
            }
        }
    }

    @Override
    public void quiteRoomComplete(int id_status, boolean succ, LiveInfoJson liveinfo) {
        Log.d(TAG, "quiteRoomComplete: ");
    }

    @Override
    public void showInviteDialog() {
        Log.d(TAG, "showInviteDialog: ");
    }

    @Override
    public void refreshText(String text, String name) {
        if (text != null) {
            refreshTextListView(name, text, Constants.TEXT_TYPE);
        }
    }

    @Override
    public void refreshThumbUp() {
        Log.d(TAG, "refreshThumbUp: ");
    }

    @Override
    public void changeCtrlView(boolean bVideoMember) {

    }

    @Override
    public boolean showInviteView(String id) {
        Log.d(TAG, "showInviteView: ");
        return false;
    }

    @Override
    public void cancelInviteView(String id) {
        Log.d(TAG, "cancelInviteView: ");
    }

    @Override
    public void cancelMemberView(String id) {
        Log.d(TAG, "cancelMemberView: ");
    }

    @Override
    public void memberJoin(String id, String name) {
        Log.i(TAG, "memberJoin: ");
        refreshTextListView(TextUtils.isEmpty(name) ? id : name, "join live", Constants.MEMBER_ENTER);
    }

    @Override
    public void hideInviteDialog() {
        Log.d(TAG, "hideInviteDialog: ");
    }

    @Override
    public void pushStreamSucc(ILivePushRes streamRes) {

    }


    @Override
    public void stopStreamSucc() {
        Log.d(TAG, "stopStreamSucc: ");
    }

    @Override
    public void startRecordCallback(boolean isSucc) {
        Log.d(TAG, "startRecordCallback: ");
    }

    @Override
    public void stopRecordCallback(boolean isSucc, List<String> files) {
        Log.d(TAG, "stopRecordCallback: ");
    }

    @Override
    public void hostLeave(String id, String name) {
        Log.d(TAG, "hostLeave: ");
        refreshTextListView("host", "leave for a while", Constants.HOST_LEAVE);
    }

    @Override
    public void hostBack(String id, String name) {
        Log.d(TAG, "hostBack: ");
        refreshTextListView(TextUtils.isEmpty(name) ? id : name, "is back", Constants.HOST_BACK);
    }

    @Override
    public void refreshMember(ArrayList<MemberID> memlist) {
        Log.d(TAG, "refreshMember: ");
    }

    @Override
    public void linkRoomReq(String id, String name) {

    }

    @Override
    public void linkRoomAccept(String id, String strRoomId) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.activity_live_send_btn:
                sendMessage();
                break;
            case R.id.activity_live_face_img:
                if (relativeLayout.getVisibility() == View.VISIBLE)
                    relativeLayout.setVisibility(View.GONE);
                else
                    relativeLayout.setVisibility(View.VISIBLE);
                break;
        }
    }

    private void sendMessage() {
        MessageModel messageModel = new MessageModel();
        String msg = editText.getText().toString();
        msg = msg.replace("face/png/", "");
        Log.i(TAG, "sendMessage: " + msg);
        messageModel.setMessage(msg);
        messageModel.setNickName("猎天");
        messageModel.setForbidName(PHONE_NUM);
        messageModel.setHeadImg("http://pic62.nipic.com/file/20150319/12632424_132215178296_2.jpg");
        String message = JSON.toJSONString(messageModel);
        TIMMessage Nmsg = new TIMMessage();
        TIMTextElem elem = new TIMTextElem();
        elem.setText(message);
        if (Nmsg.addElement(elem) != 0) {
            return;
        }
        Log.i(TAG, "sendMessage: " + message);
        ILiveRoomManager.getInstance().sendGroupMessage(Nmsg, new ILiveCallBack<TIMMessage>() {
            @Override
            public void onSuccess(TIMMessage data) {
                //发送成回显示消息内容
                for (int j = 0; j < data.getElementCount(); j++) {
                    TIMElem elem = (TIMElem) data.getElement(0);
                    TIMTextElem textElem = (TIMTextElem) elem;
                    Log.i(TAG, "onSuccess: " + textElem.getText());
                    if (data.isSelf()) {
                        refreshText(textElem.getText(), MySelfInfo.getInstance().getNickName());
                        //                        handleTextMessage(elem, MySelfInfo.getInstance().getNickName());
                    } else {
                        TIMUserProfile sendUser = data.getSenderProfile();
                        String name;
                        if (sendUser != null) {
                            name = sendUser.getNickName();
                        } else {
                            name = data.getSender();
                        }
                        refreshText(textElem.getText(), name);
                    }
                }
                SxbLog.d(TAG, "sendGroupMessage->success");
            }

            @Override
            public void onError(String module, int errCode, String errMsg) {
                Toast.makeText(LiveActivity.this, "send msg failed:" + module + "|" + errCode + "|" + errMsg, Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 消息刷新显示
     *
     * @param name    发送者
     * @param context 内容
     * @param type    类型 （上线线消息和 聊天消息）
     */
    public void refreshTextListView(String name, String context, int type) {
        Log.i(TAG, "refreshTextListView: " + context);
        ChatEntity entity = new ChatEntity();
        // TODO: 2017/2/21 修改消息接受方式
        MessageModel messageModel = new MessageModel();
        if (!context.startsWith("{")) {
            messageModel.setMessage(context);
            messageModel.setNickName("主播");
        } else {
            messageModel = JSON.parseObject(context, MessageModel.class);
        }
        entity.setSenderName(name);
        entity.setMessageModel(messageModel);
        entity.setType(type);
        //mArrayListChatEntity.add(entity);
        notifyRefreshListView(entity);
        if (listView.getCount() < 1) {
            listView.setSelection(0);
        } else {
            listView.setSelection(listView.getCount() - 1);
        }
    }

    /**
     * 通知刷新消息ListView
     */
    private void notifyRefreshListView(ChatEntity entity) {
        //        mBoolNeedRefresh = true;
        mTmpChatList.add(entity);
        //        if (mBoolRefreshLock) {
        //            return;
        //        } else {
        doRefreshListView();
        //        }
    }

    /**
     * 刷新ListView并重置状态
     */
    private void doRefreshListView() {
        //        if (mBoolNeedRefresh) {
        messageList.addAll(mTmpChatList);
        mTmpChatList.clear();
        messageAdapter.notifyDataSetChanged();
        listView.smoothScrollToPosition(messageList.size() - 1);
        //        } else {
        //            mBoolRefreshLock = false;
        //        }
    }

    /*
     * 初始表情 *
	 */
    private void InitViewPager() {
        // 获取页数
        for (int i = 0; i < getPagerCount(); i++) {
            views.add(viewPagerItem(i));
            ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(16, 16);
            mDotsLayout.addView(dotsItem(i), params);
        }
        FaceVPAdapter mVpAdapter = new FaceVPAdapter(views);
        viewPager.setAdapter(mVpAdapter);
        mDotsLayout.getChildAt(0).setSelected(true);
    }

    private ImageView dotsItem(int position) {
        LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.dot_image, null);
        ImageView iv = (ImageView) layout.findViewById(R.id.face_dot);
        iv.setId(position);
        return iv;
    }

    /**
     * 根据表情数量以及GridView设置的行数和列数计算Pager数量
     *
     * @return
     */
    private int getPagerCount() {
        int count = staticFacesList.size();
        return count % (columns * rows - 1) == 0 ? count / (columns * rows - 1)
                : count / (columns * rows - 1) + 1;
    }

    /**
     * 初始化表情列表staticFacesList
     */
    private void initStaticFaces() {
        try {
            staticFacesList = new ArrayList<String>();
            String[] faces = getAssets().list("face/png");
            // 将Assets中的表情名称转为字符串一一添加进staticFacesList
            for (int i = 0; i < faces.length; i++) {
                staticFacesList.add(faces[i]);
            }
            // 去掉删除图片
            staticFacesList.remove("emotion_del_normal.png");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private View viewPagerItem(int position) {
        LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.face_gridview, null);// 表情布局
        GridView gridview = (GridView) layout.findViewById(R.id.chart_face_gv);
        /**
         * 注：因为每一页末尾都有一个删除图标，所以每一页的实际表情columns *　rows　－　1; 空出最后一个位置给删除图标
         * */
        List<String> subList = new ArrayList<String>();
        subList.addAll(staticFacesList
                .subList(position * (columns * rows - 1),
                        (columns * rows - 1) * (position + 1) > staticFacesList
                                .size() ? staticFacesList.size() : (columns
                                * rows - 1)
                                * (position + 1)));
        /**
         * 末尾添加删除图标
         * */
        subList.add("emotion_del_normal.png");
        FaceGVAdapter mGvAdapter = new FaceGVAdapter(subList, this);
        gridview.setAdapter(mGvAdapter);
        gridview.setNumColumns(columns);
        // 单击表情执行的操作
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                try {
                    String png = ((TextView) ((LinearLayout) view)
                            .getChildAt(1)).getText().toString();
                    if (!png.contains("emotion_del_normal")) {// 如果不是删除图标
                        insert(getFace(png));
                    } else {
                        delete();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        return gridview;
    }

    /**
     * 向输入框里添加表情
     */
    private void insert(CharSequence text) {
        int iCursorStart = Selection.getSelectionStart((editText.getText()));
        int iCursorEnd = Selection.getSelectionEnd((editText.getText()));
        if (iCursorStart != iCursorEnd) {
            ((Editable) editText.getText()).replace(iCursorStart, iCursorEnd, "");
        }
        int iCursor = Selection.getSelectionEnd((editText.getText()));
        ((Editable) editText.getText()).insert(iCursor, text);
    }

    private SpannableStringBuilder getFace(String png) {
        SpannableStringBuilder sb = new SpannableStringBuilder();
        try {
            /**
             * 经过测试，虽然这里tempText被替换为png显示，但是但我单击发送按钮时，获取到輸入框的内容是tempText的值而不是png
             * 所以这里对这个tempText值做特殊处理
             * 格式：#[face/png/f_static_000.png]#，以方便判斷當前圖片是哪一個
             * */
            Log.i(TAG, "getFace: " + png);
            String tempText = getString(R.string.face_before) + png + getString(R.string.face_ofter);
            sb.append(tempText);
            sb.setSpan(
                    new ImageSpan(LiveActivity.this, BitmapFactory
                            .decodeStream(getAssets().open(png))), sb.length()
                            - tempText.length(), sb.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return sb;
    }

    /**
     * 删除图标执行事件
     * 注：如果删除的是表情，在删除时实际删除的是tempText即图片占位的字符串，所以必需一次性删除掉tempText，才能将图片删除
     */
    private void delete() {
        if (editText.getText().length() != 0) {
            int iCursorEnd = Selection.getSelectionEnd(editText.getText());
            int iCursorStart = Selection.getSelectionStart(editText.getText());
            if (iCursorEnd > 0) {
                if (iCursorEnd == iCursorStart) {
                    if (isDeletePng(iCursorEnd)) {
                        String st = getString(R.string.face_string);
                        ((Editable) editText.getText()).delete(
                                iCursorEnd - st.length(), iCursorEnd);
                    } else {
                        ((Editable) editText.getText()).delete(iCursorEnd - 1,
                                iCursorEnd);
                    }
                } else {
                    ((Editable) editText.getText()).delete(iCursorStart,
                            iCursorEnd);
                }
            }
        }
    }

    /**
     * 判断即将删除的字符串是否是图片占位字符串tempText 如果是：则讲删除整个tempText
     **/
    private boolean isDeletePng(int cursor) {
        String st = getString(R.string.face_string);
        String content = editText.getText().toString().substring(0, cursor);
        if (content.length() >= st.length()) {
            String checkStr = content.substring(content.length() - st.length(),
                    content.length());
            String regex = "(\\#\\[face/png/huikaoba_)\\d{3}(.png\\]\\#)";
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(checkStr);
            return m.matches();
        }
        return false;
    }
}
